package com.magicalcoder.youyamvc.web.controller.web.classteacher;
import com.magicalcoder.youyamvc.app.classteacher.service.ClassTeacherService;
import com.magicalcoder.youyamvc.app.classteacher.service.ClassTeacherProxyService;
import com.magicalcoder.youyamvc.app.classteacher.constant.ClassTeacherConstant;
import com.magicalcoder.youyamvc.app.classteacher.util.ClassTeacherUtil;
import com.magicalcoder.youyamvc.web.controller.web.classteacher.param.ClassTeacherRequest;
import com.magicalcoder.youyamvc.web.controller.web.classteacher.param.ClassTeacherResponse;
import com.magicalcoder.youyamvc.app.model.ClassTeacher;
import com.magicalcoder.youyamvc.core.common.utils.ProjectUtil;
import com.magicalcoder.youyamvc.core.common.utils.MapUtil;
import com.magicalcoder.youyamvc.core.common.utils.ListUtils;
import com.magicalcoder.youyamvc.core.common.utils.StringUtils;
import com.magicalcoder.youyamvc.core.common.dto.AjaxData;
import com.magicalcoder.youyamvc.core.common.utils.copy.Copyer;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginController;
import com.magicalcoder.youyamvc.core.spring.web.WebLoginController;
import com.magicalcoder.youyamvc.web.common.BaseController;
import com.magicalcoder.youyamvc.app.userweb.util.UserWebUtil;
import com.magicalcoder.youyamvc.core.common.exception.BusinessException;

import org.springframework.format.annotation.DateTimeFormat;
import java.util.*;
import java.math.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;

/**
* 代码为自动生成 Created by www.magicalcoder.com
* 如果你改变了此类 read 请将此行删除
* 欢迎加入官方QQ群:323237052
*/

@RequestMapping({"/user/class_teacher"})
@Controller
public class ClassTeacherUserController extends WebLoginController
{

    @Resource
    private ClassTeacherService classTeacherService;
    @Resource
    private ClassTeacherProxyService classTeacherProxyService;
    /** method:GET
    *   url:/user/class_teacher/list/{pageIndex}/{pageSize}?...
    *   demo:/user/class_teacher/list/1/20
    *   获取班级关联教师分页数据
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  是   @pageIndex                     (Integer)当前页码 [1,n]
    *  是   @pageSize                      (Integer)每页条数 [1,n]
    *  否   @callback                      (String)回调方法
    *  否   @orderBySqlField               (String)排序字段
    *  否   @descAsc                       (String)desc|asc
    *  否   @encode                        (String)编码 默认UTF-8
    *  否   @id                     (Long)班级关联老师表主键 11113
    *  否   @classId                     (Long)班级表主键 
    *  否   @teacherId                     (Long)老师表主键 
    *  否  in @classIdFirst                     (Long)班级表主键 
    *  否  in @teacherIdFirst                     (Long)老师表主键 
    *  返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:
                [{
    *              id         (Long)班级关联老师表主键 11113
    *              classId         (Long)班级表主键 
    *              teacherId         (Long)老师表主键 
    *      }]
    *   }
    */
    @RequestMapping(value={"list/{pageIndex}/{pageSize}"}, method={RequestMethod.GET})
    public void list(@PathVariable Integer pageIndex,@PathVariable Integer pageSize,
        @RequestParam(required=false, value="orderBySqlField") String orderBySqlField,
        @RequestParam(required=false, value="descAsc") String descAsc,
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")   Long id,
        @RequestParam(required = false,value ="classId")   Long classId,
        @RequestParam(required = false,value ="teacherId")   Long teacherId,
        @RequestParam(required = false,value ="classIdFirst")                            String classIdFirst ,
        @RequestParam(required = false,value ="teacherIdFirst")                            String teacherIdFirst ,
        HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)
    {
        try{
            String orderBySqlFieldStr = ",id,class_id,teacher_id,";
            String orderBy = ProjectUtil.filterOrderBy(orderBySqlFieldStr,orderBySqlField,descAsc);
            if(StringUtils.isBlank(orderBy)){
                orderBy = "teacher_id asc";
            }
            pageSize = Math.min(ClassTeacherConstant.PAGE_MAX_SIZE,pageSize);
            int idx = (pageIndex.intValue() - 1) * pageSize;
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap("orderBy", orderBy,
         "id",id,
         "classId",classId,
         "teacherId",teacherId,
                    "classIdFirst",ProjectUtil.toList(classIdFirst ,Long.class),
                    "teacherIdFirst",ProjectUtil.toList(teacherIdFirst ,Long.class),
                "start",idx,"limit", pageSize ,"userId",_userId);

            List<ClassTeacher> pageList = this.classTeacherService.getClassTeacherList(query);
            toWebSuccessJson(callback,encode,response, coverToResponseList(pageList));
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    private List<ClassTeacherResponse> coverToResponseList(List<ClassTeacher> pageList){
        if(ListUtils.isBlank(pageList)){
            return null;
        }
        return Copyer.copy(pageList,ClassTeacherResponse.class);
    }


    /** method:GET
    *   url:/user/class_teacher/item?...
    *   demo:/user/class_teacher/item
    *   获取班级关联教师详情数据
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  否   @callback                      (String)回调方法
    *  否   @encode                        (String)编码 默认UTF-8
     *  否  @id        (Long) 主键
    *  返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:
                {
    *              id         (Long)班级关联老师表主键 11113
    *              classId         (Long)班级表主键 
    *              teacherId         (Long)老师表主键 
    *      }
    *   }
    */
    @RequestMapping(value={"item"}, method={RequestMethod.GET})
    public void item(
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")Long id,
        HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)
    {
        try{
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap(
                     "id",id,
                "userId",_userId
            );
            ClassTeacher classTeacher = this.classTeacherService.selectFirstClassTeacher(query);
            toWebSuccessJson(callback,encode,response, Copyer.copy(classTeacher,new ClassTeacherResponse()));
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    /** method:post
    *   url:/user/class_teacher/save?...
    *   demo:/user/class_teacher/save?...
    *   保存班级关联教师
    *   是否需要登录               是
    *是否必须         入参         注释
    * 否id (Long)班级关联老师表主键 11113 为空表示插入否则表示更新
    * 否classId (Long)班级表主键  
    * 否teacherId (Long)老师表主键  
    *
    *   返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:id 主键 Long
    *   }
    */
    @RequestMapping(value={"save"}  ,method={RequestMethod.POST})
    public void save(@ModelAttribute ClassTeacherRequest classTeacherRequest,

        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        HttpServletRequest request,HttpServletResponse response) {
        Long _userId = UserWebUtil.userId(request);
        try{
            Long id = saveEntity(_userId,classTeacherRequest);
            toWebSuccessJson(callback,encode,response, id);
        }catch (BusinessException e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(callback,encode,response,e.getErrorCode(), exceptionMsg);
            e.printStackTrace();
        }
        catch (Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(callback,encode,response, exceptionMsg);
            e.printStackTrace();
        }
    }

    private Long saveEntity(Long userId,ClassTeacherRequest classTeacherRequest){
        if (classTeacherRequest.getId() == null) {
            ClassTeacher classTeacher = new ClassTeacher();
            Copyer.copy(classTeacherRequest,classTeacher);
            return this.classTeacherService.insertClassTeacher(classTeacher);
        } else {
            ClassTeacher entity = getEntity(userId,classTeacherRequest.getId());
            if(entity!=null){
                Copyer.reflectCopyZeroNotNull(classTeacherRequest, entity);
                this.classTeacherService.updateClassTeacher(entity);
            }
        }
        return classTeacherRequest.getId();
    }

    private ClassTeacher getEntity(Long userId,Long id){
        return this.classTeacherService.selectOneClassTeacherWillThrowException(ProjectUtil.buildMap(
            "id",id));
    }

    /** method:get
    *   url:/user/class_teacher/delete?...
    *   demo:/user/class_teacher/delete?...

    *   删除班级关联教师
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  否   @callback                      (String)回调方法
    *  否   @encode                        (String)编码 默认UTF-8
    *  否  @id        (Long) 主键
    *   返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:true||false
    *   }
    */
    @RequestMapping(value={"delete"}, method={RequestMethod.GET})
    public void delete(
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")Long id,
    HttpServletRequest request,HttpServletResponse response)
    {
        try{
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap(
            "id",id,
            "userId",_userId
            );
            this.classTeacherService.deleteClassTeacherList(query);
            toWebSuccessJson(callback,encode,response, true);
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }



}